#include "stdafx.h"
#include "XSkinCoreImpl.h"

#include "Util.h"
#include "FileUtil.h"
#include "XCodeDefine.h"

#include "IXFileSystem.h"
#include "IXStringBundleMgr.h"

#include "IntMenuHook.h"

IMPLEMENT_SKIN_CLASS(CXSkinCoreImpl);


CXSkinCoreImpl::CXSkinCoreImpl()
{
    m_uGdiplusToken = 0;
    m_hOleInitResult = E_NOTIMPL;
}

CXSkinCoreImpl::~CXSkinCoreImpl()
{
    ;
}

//////////////////////////////////////////////////////////////////////////
// IXSkinCore
HRESULT CXSkinCoreImpl::InitCore(IN LPCTSTR szSkinRootPath, IN LPCTSTR szLanguage)
{
    Gdiplus::GdiplusStartupInput input;
    Gdiplus::Status status = Gdiplus::GdiplusStartup(&m_uGdiplusToken, &input, NULL);
    if(status != Gdiplus::Ok)
        return E_FAIL;

    m_hOleInitResult = OleInitialize(NULL);
    CHECK_HRESULT(m_hOleInitResult);

    INITCOMMONCONTROLSEX InitCtrls;
    InitCtrls.dwSize = sizeof(InitCtrls);
    InitCtrls.dwICC = ICC_WIN95_CLASSES;
    if(!InitCommonControlsEx(&InitCtrls))
        return E_FAIL;

    InitMenuHook();

    BOOL bLoadFromRes = FALSE;

    {
        XInstPtr<IXFileSystem> pFileSystem;
        if(pFileSystem != NULL)
        {
            bLoadFromRes = pFileSystem->get_LoadFromRes();
        }
    }

    if(!bLoadFromRes && (szSkinRootPath == NULL || szSkinRootPath[0] == 0))
        return S_FALSE;

    XPtr<IXFileSystem> pFS = NULL;

    HRESULT hResult = Util::CreateObject(&pFS);
    CHECK_HRESULT(hResult);

    hResult = pFS->put_XNCFile(szSkinRootPath);
    CHECK_HRESULT(hResult);

    // StringBundle
    if(!bLoadFromRes)
        hResult = InitStringBundle(szSkinRootPath, szLanguage);

    return hResult;
}

HRESULT CXSkinCoreImpl::InitStringBundle(IN LPCTSTR szSkinRootPath, IN LPCTSTR szLanguage)
{
    IXStringBundleMgr* pStringBundleMgr = NULL;
    HRESULT hResult = Util::CreateObject(&pStringBundleMgr);
    if(SUCCEEDED(hResult))
    {
        hResult = pStringBundleMgr->InitStringBundleMgr(szSkinRootPath, szLanguage);
        pStringBundleMgr->Release();
    }
    return hResult;
}

HRESULT CXSkinCoreImpl::DestroyCore()
{
    UnInitMenuHook();

    if(m_uGdiplusToken != 0)
    {
        Gdiplus::GdiplusShutdown(m_uGdiplusToken);
        m_uGdiplusToken = 0;
    }
    if(SUCCEEDED(m_hOleInitResult))
    {
        OleUninitialize();
        m_hOleInitResult = E_NOTIMPL;
    }
    return S_OK;
}

